package com.hyjy.music.util

import android.content.Context
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.DrawableRes
import androidx.annotation.IdRes
import androidx.annotation.LayoutRes

/**
 * 通用Adapter
 */
abstract class CommonAdapter<T> constructor(
    private var context: Context,
    private var dataList: List<T>,
    @LayoutRes private var itemLayoutRes: Int
) : BaseAdapter() {
    override fun getCount(): Int = dataList.size

    override fun getItem(position: Int): T = dataList[position]

    override fun getItemId(position: Int): Long = position.toLong()

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        val view: View
        val viewHolder: ViewHolder
        if (convertView == null) {
            view = LayoutInflater.from(context).inflate(itemLayoutRes, parent, false)
            viewHolder = ViewHolder()
            getItemViewId().forEach {
                viewHolder.viewCache[it] = view.findViewById(it)
            }
            view.tag = viewHolder
        } else {
            view = convertView
            viewHolder = view.tag as ViewHolder
        }
        getView(viewHolder, position, getItem(position))
        return view
    }

    /**
     * 返回Item中所有View的id
     */
    abstract fun getItemViewId(): IntArray

    abstract fun getView(viewHolder: ViewHolder, position: Int, item: T)

    /**
     * 刷新数据
     *
     * @param list 新的数据源
     */
    fun refreshData(list: List<T>) {
        this.dataList = list
        notifyDataSetChanged()
    }

    class ViewHolder {
        var viewCache: SparseArray<View> = SparseArray()

        /**
         * 通过控件的Id获取对应的控件，如果没有则加入views
         */
        inline fun <reified T : View> getItemView(@IdRes viewId: Int): T? {
            val view = viewCache[viewId]
            return if (view is T) {
                view
            } else {
                null
            }
        }

        /**
         * 给TextView赋值
         */
        fun setTextView(@IdRes id: Int, text: String?): ViewHolder {
            getItemView<TextView>(id)?.text = text
            return this
        }

        /**
         * 给ImageView赋值
         */
        fun setImageView(@IdRes id: Int, @DrawableRes drawableId: Int): ViewHolder {
            getItemView<ImageView>(id)?.setImageResource(drawableId)
            return this
        }
    }
}